import React, { useState, useCallback, useMemo } from 'react';
import { Modal, Form, Input, Select, Button, message } from 'antd';
import moment from 'moment';
import { Student, StudentForAdd, StudentForEdit, addStudent, editStudent } from '@/utils/api/student/student';

const { Option } = Select;

interface StudentFormModalProps {
    visible: boolean;
    onCancel: () => void;
    onSubmitSuccess: () => void;
    currentStudent: Student | null;
    currentId: number | null;
    departmentOptions: string[];
    allMajorOptions: string[];
    departmentMajorMap: Map<string, string[]>;
    fetchAllData: () => Promise<void>;
}

const StudentFormModal: React.FC<StudentFormModalProps> = ({
                                                               visible,
                                                               onCancel,
                                                               onSubmitSuccess,
                                                               currentStudent,
                                                               currentId,
                                                               departmentOptions,
                                                               allMajorOptions,
                                                               departmentMajorMap,
                                                               fetchAllData
                                                           }) => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [selectedDepartment, setSelectedDepartment] = useState<string>('');
    const [showAllMajors, setShowAllMajors] = useState<boolean>(true);

    // 生成年份选项
    const yearOptions = useMemo(() => {
        const currentYear = moment().year();
        const startYear = currentYear - 10;
        const endYear = currentYear + 1;
        const years = [];

        for (let year = startYear; year <= endYear; year++) {
            years.push(year);
        }

        return years.reverse();
    }, []);

    // 处理身份证号失去焦点
    const handleIdCardBlur = useCallback((e: React.FocusEvent<HTMLInputElement>) => {
        const idCard = e.target.value;
        const idCardPattern = /(^\d{18$)|(^\d{17}(\d|X|x)$)/;

        if (!idCardPattern.test(idCard) && idCard.length > 0) {
            message.error('请输入有效的18位身份证号');
        }
    }, []);

    // 处理手机号失去焦点
    const handlePhoneBlur = useCallback((e: React.FocusEvent<HTMLInputElement>) => {
        const phone = e.target.value;
        const phonePattern = /^1[3-9]\d{9}$/;

        if (!phonePattern.test(phone) && phone.length > 0) {
            message.error('请输入有效的11位手机号');
        }
    }, []);

    // 院系选择变化处理
    const handleDepartmentChange = useCallback((value: string) => {
        setSelectedDepartment(value);
        form.setFieldsValue({ major: undefined });

        if (value) {
            setShowAllMajors(false);
        } else {
            setShowAllMajors(true);
        }
    }, [form]);

    // 提交表单
    const handleSubmit = useCallback(async () => {
        try {
            const values = await form.validateFields();
            setLoading(true);

            if (currentId) {
                const editData: StudentForEdit = {
                    id: currentId,
                    studentNumber: values.studentNumber,
                    name: values.name,
                    idCard: values.idCard,
                    phone: values.phone,
                    grade: values.grade,
                    department: values.department,
                    major: values.major,
                    createTime: currentStudent?.createTime ?
                        moment(currentStudent.createTime).format('YYYY-MM-DD HH:mm:ss') :
                        moment().format('YYYY-MM-DD HH:mm:ss'),
                    groupId: currentStudent?.groupId
                };

                await editStudent(editData);
                message.success("编辑成功");
            } else {
                const addData: StudentForAdd = {
                    name: values.name,
                    studentNumber: values.studentNumber,
                    idCard: values.idCard,
                    phone: values.phone,
                    grade: values.grade,
                    department: values.department,
                    major: values.major
                };

                await addStudent(addData);
                message.success("添加成功");
            }

            onSubmitSuccess();
            onCancel();
        } catch (error) {
            console.error('操作失败:', error);
        } finally {
            setLoading(false);
        }
    }, [form, currentId, currentStudent, onSubmitSuccess, onCancel]);

    // 初始化表单值
    React.useEffect(() => {
        if (visible && currentStudent) {
            form.setFieldsValue({
                studentNumber: currentStudent.studentNumber,
                name: currentStudent.name,
                idCard: currentStudent.idCard,
                phone: currentStudent.phone,
                grade: currentStudent.grade,
                department: currentStudent.department,
                major: currentStudent.major
            });

            if (currentStudent.department) {
                setSelectedDepartment(currentStudent.department);
                setShowAllMajors(false);
            } else {
                setShowAllMajors(true);
            }
        } else if (visible) {
            form.resetFields();
            setSelectedDepartment('');
            setShowAllMajors(true);
        }
    }, [visible, currentStudent, form]);

    return (
        <Modal
            title={currentId ? "编辑学生" : "新增学生"}
            open={visible}
            onCancel={onCancel}
            footer={[
                <Button key="cancel" onClick={onCancel}>
                    取消
                </Button>,
                <Button key="submit" type="primary" loading={loading} onClick={handleSubmit}>
                    确定
                </Button>,
            ]}
            destroyOnClose={true}
            width={600}
        >
            <Form form={form} layout="vertical">
                <Form.Item
                    name="name"
                    label="姓名"
                    rules={[{ required: true, message: '请输入姓名' }]}
                >
                    <Input placeholder="请输入姓名" />
                </Form.Item>

                <Form.Item
                    name="studentNumber"
                    label="学号"
                    rules={[{ required: true, message: '请输入学号' }]}
                >
                    <Input placeholder="请输入学号" />
                </Form.Item>

                <Form.Item
                    name="idCard"
                    label="身份证号"
                    rules={[
                        { required: true, message: '请输入身份证号' },
                        {
                            pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                            message: '请输入有效的18位身份证号'
                        }
                    ]}
                >
                    <Input
                        placeholder="请输入身份证号"
                        maxLength={18}
                        onBlur={handleIdCardBlur}
                    />
                </Form.Item>

                <Form.Item
                    name="grade"
                    label="年级"
                    rules={[{ required: true, message: '请选择入学年份' }]}
                >
                    <Select placeholder="请选择入学年份">
                        {yearOptions.map(year => (
                            <Option key={year} value={String(year)}>
                                {year}级
                            </Option>
                        ))}
                    </Select>
                </Form.Item>

                <Form.Item
                    name="department"
                    label="院系"
                    rules={[{ required: true, message: '请选择院系' }]}
                >
                    <Select
                        placeholder="请选择院系"
                        onChange={handleDepartmentChange}
                        allowClear
                        onFocus={fetchAllData}
                    >
                        {departmentOptions.map(dept => (
                            <Option key={dept} value={dept}>
                                {dept}
                            </Option>
                        ))}
                    </Select>
                </Form.Item>

                <Form.Item
                    name="major"
                    label="专业"
                    rules={[{ required: true, message: '请选择专业' }]}
                >
                    <Select
                        placeholder="请选择专业"
                        allowClear
                        onFocus={fetchAllData}
                    >
                        {showAllMajors ? allMajorOptions.map(major => (
                            <Option key={major} value={major}>
                                {major}
                            </Option>
                        )) : (selectedDepartment ?
                                (departmentMajorMap.get(selectedDepartment) || []).map(major => (
                                    <Option key={major} value={major}>
                                        {major}
                                    </Option>
                                )) : allMajorOptions.map(major => (
                                    <Option key={major} value={major}>
                                        {major}
                                    </Option>
                                ))
                        )}
                    </Select>
                </Form.Item>

                <Form.Item
                    name="phone"
                    label="手机号"
                    rules={[
                        { required: true, message: '请输入手机号' },
                        {
                            pattern: /^1[3-9]\d{9}$/,
                            message: '请输入有效的11位手机号'
                        }
                    ]}
                >
                    <Input
                        placeholder="请输入手机号"
                        maxLength={11}
                        onBlur={handlePhoneBlur}
                    />
                </Form.Item>

                <Form.Item label="创建时间">
                    <Input
                        disabled
                        value={currentId && currentStudent ?
                            moment(currentStudent.createTime).format('YYYY-MM-DD HH:mm:ss') :
                            "系统自动生成"
                        }
                    />
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default React.memo(StudentFormModal);